package service

import (
	"fmt"
	"log"
	"os"
	"path"

	"gitee.com/anxu/golang-web/src/config"
)

const (
	defaultLogPath = "runtime/logs"
	defaultLogFile = "app.log"
	defaultStdout  = true
)

// Logger logger
var Logger *logger

// error level
const (
	LevelError   = "error"
	LevelInfo    = "info"
	LevelWarning = "warning"
)

func init() {
	logPath := config.Config.Get("logger.path", defaultLogPath).(string)
	logFile := config.Config.Get("logger.file", defaultLogFile).(string)
	stdout := config.Config.Get("logger.stdout", defaultStdout).(bool)
	Logger = &logger{log: new(logPath, logFile), stdout: stdout}
}

type logger struct {
	log    *log.Logger
	stdout bool
}

func new(logPath, fileName string) *log.Logger {
	if _, err := os.Stat(logPath); os.IsNotExist(err) {
		os.Mkdir(logPath, 0666)
	}
	file, err := os.OpenFile(path.Join(logPath, fileName), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("Failed to open log file", err)
	}
	return log.New(file, "", log.LstdFlags|log.Lshortfile|log.Lmsgprefix)
}

func (l *logger) Error(message interface{}) {
	l.write(message, LevelInfo)
}

func (l *logger) Info(message interface{}) {
	l.write(message, LevelInfo)
}

func (l *logger) Warning(message interface{}) {
	l.write(message, LevelWarning)
}

func (l *logger) write(message interface{}, level string) {
	l.log.SetPrefix(fmt.Sprintf("[%s] ", level))
	l.log.Println(message)
	if l.stdout {
		log.Println(fmt.Sprintf("[%s] ", level), message)
	}
}
